package com.jiangnan.warehouse_management.interceptor;

import com.jiangnan.warehouse_management.common.Result;
import com.jiangnan.warehouse_management.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class GlobalInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        
        // 排除登录和注册接口
        if (requestURI.equals("/api/auth/login") || requestURI.equals("/api/users")) {
            return true;
        }

        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            handleUnauthorized(response, "未提供有效的认证信息");
            return false;
        }

        // 提取token
        String token = authHeader.substring(7);
        
        try {
            // 验证token
            if (!JwtUtils.validateToken(token)) {
                handleUnauthorized(response, "token已过期或无效");
                return false;
            }
            return true;
        } catch (Exception e) {
            handleUnauthorized(response, "token验证失败");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清除ThreadLocal中的用户信息
        JwtUtils.clearCurrentUser();
    }

    private void handleUnauthorized(HttpServletResponse response, String message) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(objectMapper.writeValueAsString(Result.fail(401, message)));
    }
}
